package com.leetcode.partition10;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/9/10 9:40
 */
public class LC977有序数组的平方 {

    public static int[] sortedSquares(int[] nums) {
        return doubleIndex(nums);
    }

    public static void main(String[] args) {
        int[] nums = {-7, -3, 2, 3, 11};
        System.out.println(Arrays.toString(sortedSquares(nums)));
    }

    private static int[] doubleIndex(final int[] nums) {
        int[] answer = new int[nums.length];
        int index = answer.length - 1;          //从后往前放

        for (int left = 0, right = nums.length - 1; left <= right; index--) {
            //最大值只会出现在nums的最左边或者最右边，因此index为返回数组的当前最大的索引
            int leftValue = nums[left] * nums[left], rightValue = nums[right] * nums[right];
            if (leftValue < rightValue) {
                answer[index] = rightValue;
                right--;
            } else {
                answer[index] = leftValue;
                left++;
            }
        }
        return answer;
    }
}
